<?php

namespace App\Models;


use App\Models\Traits\DataScopeHelper;
use EloquentFilter\Filterable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Hash;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;


class SysUser extends Authenticatable implements JWTSubject
{
    use HasApiTokens, HasFactory, Notifiable;
    //模型字段过滤器
    use Filterable;
    use DataScopeHelper;


    protected $dateFormat = 'U';
    protected $fillable = [
        'dept_id',
        'username',
        'nickname',
        'user_type',
        'phonenumber',
        'password',
        'status',
        'login_ip',
        'login_time',
        'create_by',
        'update_by',
        'created_at',
        'updated_at',
        'remark',
        'sec_ip',
        'group_id',
        'kc_timeout',
        'api_secret',
        'can_api',
        'can_web',
        'is_voucher',
        "phone_max",
        "pay_type",
    ];
    protected $casts = [
        'status' => 'string',
    ];
    protected $hidden = [
        'password',
    ];


    public function dept()
    {
        return $this->belongsTo(SysDept::class, 'dept_id', 'id');
    }
    public function roles()
    {
        return $this->belongsToMany(SysRole::class, 'sys_user_role', 'user_id', 'role_id');
    }

    public function group()
    {
        return $this->belongsTo(UserGroup::class, 'group_id', 'id');
    }

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
    /**
     * 为 array / JSON 序列化准备日期格式
     *
     * @param  \DateTimeInterface  $date
     * @return string
     */
    protected function serializeDate(\DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public static function boot()
    {
        parent::boot();
        //监听模型创建事件
        static::creating(function ($model) {
            if ($model->isFillable('create_by')) {
                $model->create_by = auth()->id() ?? -1;
            }
            if ($model->isFillable('update_by')) {
                $model->update_by = auth()->id() ?? -1;
            }
            if ($model->isFillable('api_secret')) {
                $model->api_secret = md5(uniqid() . rand(1000, 9999));
            }
        });
        //监听模型更新之前事件 todo判断数据权限
        static::updating(function ($model) {
            if ($model->id == 1 && auth()->id() != 1) {
                throw new HttpResponseException(error('非法更新操作[已记录]'));
            }
            if ($model->isFillable('create_by')) {
                //获取权限范围id
                $scope_info = $model->getCreateByIds();
                if ($model->isFillable('create_by') && $scope_info['scope'] == 'limit' && !in_array($model->create_by, $scope_info['ids'])) {
                    throw new HttpResponseException(error('非法操作更新数据'));
                }
                unset($model->attributes['create_by']);
            }
            //获取当前登录用户ID
            if ($model->isFillable('update_by')) {
                $model->update_by = auth()->id() ?? -1;
            }
        });

        //监听模型删除之前事件 todo判断数据权限
        static::deleting(function ($model) {
            if ($model->id == 1 && auth()->id() != 1) {
                throw new HttpResponseException(error('非法删除操作[已记录]'));
            }
            if ($model->isFillable('create_by')) {
                //获取权限范围id
                $scope_info = $model->getCreateByIds();
                if ($model->isFillable('create_by') && $scope_info['scope'] == 'limit' && !in_array($model->create_by, $scope_info['ids'])) {
                    throw new HttpResponseException(error('非法操作删除数据'));
                }
            }
        });
    }

    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = Hash::make($value);
    }
}
